package lew.bing.gwalo.rateLimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by 刘国兵 on 2018/7/8.
 */
public abstract class DefaultLimiter implements Limiter{

    private Map<String,Ratter> ratterMap = new ConcurrentHashMap<>();

    @Override
    public synchronized RateLimiter takeLimiter(String group, String key, int defaultRate) {
        String k = group + ":" + key;
        if (ratterMap.containsKey(k)) {
            return ratterMap.get(k).getLimiter();
        } else {
            Ratter ratter = new Ratter(RateLimiter.create(defaultRate),defaultRate);
            ratterMap.put(k,ratter);
            return ratter.getLimiter();
        }
    }

    public void changeRate(String k,int rate) {
        if (ratterMap.containsKey(k)) {
            Ratter ratter = ratterMap.get(k);
            if (ratter.getLastRate() != rate) {
                ratter.getLimiter().setRate(rate);
            }
        } else {
            Ratter ratter = new Ratter(RateLimiter.create(rate),rate);
            ratterMap.put(k,ratter);
        }
    }

    public abstract Map<String,Integer> rates(); // 抽象的方法

    public synchronized void changeRate() {// 存在有读与写，所以需要加锁
        if (rates() != null) {
            for (String k: rates().keySet()) {
                changeRate(k,rates().get(k));
            }
        }
    }

    public synchronized void changeRate(String key) {// 改变key的速率
        if (rates() != null && rates().containsKey(key)) {
            changeRate(key,rates().get(key));
        }
    }

}
